package com.intellagric.service.facility;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.intellagric.common.bean.LayuiDataGridResult;
import com.intellagric.common.bean.ResponseMessage;
import com.intellagric.common.utils.UUIDUtils;
import com.intellagric.dao.facility.FacilityDao;
import com.intellagric.interfaces.facility.FacilityService;
import com.intellagric.mapper.*;
import com.intellagric.pojo.*;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class FacilityServiceImpl implements FacilityService {
    @Autowired
    private FacilityMapper mapper;

    @Autowired
    private FacilityDao dao;

    @Autowired
    private FacilityUsedMapper usedMapper;

    @Autowired
    private FacilityCategoryMapper facilityCategoryMapper;

    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private FileStorageMapper fileStorageMapper;

    //返回msg格式
    public ResponseMessage selectFacilityById(String id) {
        ResponseMessage msg=new ResponseMessage();
        msg.add("facilityBean",mapper.selectByPrimaryKey(id));
        return msg;
    }
    //返回bean格式
    public Facility queryFacilityById(String id) {
        FacilityExample example=new FacilityExample();
        example.createCriteria().andFacilityIdEqualTo(id);
        List<Facility> list=mapper.selectByExample(example);
        return list.get(0);
    }

    public ResponseMessage insertFacility(Facility Facility) {
        int i=mapper.insertSelective(Facility);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }

    public ResponseMessage deleteFacility(String id) {
        FacilityExample example=new FacilityExample();
        example.createCriteria().andFacilityIdEqualTo(id);
        int i=mapper.deleteByExample(example);
        if (i!=0) {
            return ResponseMessage.success();
        }

        return ResponseMessage.fail();
    }

    public ResponseMessage editFacility(Facility Facility) {
        FacilityExample example=new FacilityExample();
        example.createCriteria().andFacilityIdEqualTo(Facility.getFacilityId());
        int i =mapper.updateByExampleSelective(Facility,example);
        if (i!=0)
            return ResponseMessage.success();
        return ResponseMessage.fail();
    }



    public LayuiDataGridResult getList(int page, int limit) {
        PageHelper.startPage(page,limit);
        FacilityExample example=new FacilityExample();
        example.createCriteria().andFacilityIdIsNotNull();
        List<Facility> list=mapper.selectByExample(example);
//        List<Facility> list=dao.selectList();
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    public LayuiDataGridResult getListByCategoryId(int page, int limit, String categoryId) {
        PageHelper.startPage(page,limit);
        FacilityExample example=new FacilityExample();
        //如果已经报废的就不要
        example.createCriteria().andCategoryIdEqualTo(categoryId).andStatusEqualTo("0");
        List<Facility> list=mapper.selectByExample(example);
//        List<Facility> list=dao.selectListByCategory(categoryId);
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    public LayuiDataGridResult batchDeleteFacility(String[] ids) {
        int i=dao.batchDeleteByPrimaryKey(ids);
        if (i!=0) {
            for (String id:ids){
                FacilityUsedExample example=new FacilityUsedExample();
                example.createCriteria().andFacilityIdEqualTo(id);
                usedMapper.deleteByExample(example);
            }
            LayuiDataGridResult result = new LayuiDataGridResult();
            result.setCode(200);
            return result;
        }
        return LayuiDataGridResult.fail();
    }

    public LayuiDataGridResult batchDelete(String[] ids) {
        int i=dao.batchDelete(ids);
        if (i!=0) {
            for (String id:ids){
                FacilityUsedExample example=new FacilityUsedExample();
                example.createCriteria().andFacilityIdEqualTo(id);
                usedMapper.deleteByExample(example);
            }
            LayuiDataGridResult result = new LayuiDataGridResult();
            result.setCode(200);
            return result;
        }
        return LayuiDataGridResult.fail();
    }

    public LayuiDataGridResult getFacilityByKeyword(int page, int limit, String keyword) {
        PageHelper.startPage(page,limit);
        FacilityExample example=new FacilityExample();
        example.createCriteria().andFacilityNameLike("%"+keyword+"%");
        example.or().andFacilityIdLike("%"+keyword+"%");
        List<Facility> list=mapper.selectByExample(example);

//        FacilityExample example2=new FacilityExample();
//        example2.createCriteria().andFacilityIdLike("%"+keyword+"%");
//        List<Facility> list2=mapper.selectByExample(example2);
//
//        list.addAll(list2);

//        List<Facility> list=dao.selectListByKeyword(keyword);
        PageInfo info=new PageInfo(list);
        return LayuiDataGridResult.success().add(list,info.getTotal());
    }

    @Override
    public LayuiDataGridResult addFacilityExcelData(MultipartFile uploadFile) {
        FacilityCategoryExample categoryExample=new FacilityCategoryExample();
        categoryExample.createCriteria().andIdIsNotNull();
        List<FacilityCategory> categoryList=facilityCategoryMapper.selectByExample(categoryExample);
        StorageExample storageExample=new StorageExample();
        storageExample.createCriteria().andStorageIdIsNotNull();
        List<Storage> storageList=storageMapper.selectByExample(storageExample);
        FileStorageExample fileStorageExample=new FileStorageExample();
        fileStorageExample.createCriteria().andStorageIdIsNotNull();
        List<FileStorage> fileStorageList=fileStorageMapper.selectByExample(fileStorageExample);
        List<String> facilityList=new ArrayList<>();
        List<String> facilityIds=new ArrayList<>();
        LayuiDataGridResult result=new LayuiDataGridResult();
        try {
            /*POIFSFileSystem fileSystem=new POIFSFileSystem(uploadFile.getInputStream());
            HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);*/
            Boolean first=true;
            Workbook workbook= WorkbookFactory.create(uploadFile.getInputStream());
            Sheet sheet=workbook.getSheetAt(0);//第一页
            for (Row row:sheet) {
                if (first) {
                    first = false;
                    continue;
                }
                StringBuilder facility=new StringBuilder();
                Boolean available = false;

                for (int i=0,j=row.getLastCellNum();i<j;i++){
                    if(i==0){
                        if(row.getCell(i)==null||row.getCell(i).toString().equals(""))
                            break;
                        String categoryName=row.getCell(0).toString();
                        for (FacilityCategory category:categoryList){
                            if (category.getName().equals(categoryName)){
                                available=true;
                                String id= UUIDUtils.getID();
                                facility.append(id);
                                facilityIds.add(id);
                                facility.append("!"+category.getId());
                                break;
                            }
                        }
                        continue;
                    }
                    if (!available){
                        break;
                    }
                    if (CellType.NUMERIC.compareTo(row.getCell(i).getCellType())==0) {
                        if (HSSFDateUtil.isCellDateFormatted(row.getCell(i))) {
                            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd");
                            facility.append("!"+simpleDateFormat.format(row.getCell(i).getDateCellValue()));
                            continue;
                        }
                    }
                    int k=row.getLastCellNum();
                    if(i==k-5){
                        if(row.getCell(i)==null||row.getCell(i).toString().equals(""))
                        {
                            facility.append("!"+"0");
                            continue;
                        }
                        if (row.getCell(i).toString().equals("报废")){
                            facility.append("!"+"1");
                            continue;
                        }else {
                            facility.append("!" + "0");
                            continue;
                        }

                    }

                    if (i==k-1){
                        if(row.getCell(i)==null||row.getCell(i).toString().equals(""))
                        {
                            facility.append("!");
                            continue;
                        }
                        String storageName=row.getCell(i).toString();
                        int index=storageName.indexOf(".");
                        if(index!=-1) {
                            storageName = storageName.substring(0, index);
                        }
                        for (Storage storage:storageList){
                            if (storage.getName().equals(storageName)){
                                facility.append("!"+storage.getStorageId());
                                break;
                            }
                        }
                    }else if(i==k-2){

                        if(row.getCell(i)==null||row.getCell(i).toString().equals(""))
                        {
                            facility.append("!");
                            continue;
                        }
                        String storageName=row.getCell(i).toString();
                        int index=storageName.indexOf(".");
                        if(index!=-1) {
                            storageName = storageName.substring(0, index + 1);
                        }
                        for (FileStorage storage:fileStorageList){
                            if (storage.getName().equals(storageName)){
                                facility.append("!"+storage.getStorageId());
                                break;
                            }
                        }
                    }
                    else{
                        DecimalFormat df = new DecimalFormat("0");
                        String cellValue=row.getCell(i).toString();
                        if (CellType.NUMERIC.compareTo(row.getCell(i).getCellType())==0) {
                            cellValue = df.format(row.getCell(i).getNumericCellValue());
                        }
                        facility.append("!"+cellValue);
                    }
                }
                if(available) {
                    facilityList.add(facility.toString());
                }
            }
            int i=dao.batchInsert(facilityList);
            if (i==facilityList.size()){
                result.setCode(0);
                result.setCount(i);
                result.setMsg("新增"+i+"条数据");
                result.setData(facilityIds);
                return result;
            }else
                return LayuiDataGridResult.fail();
        } catch (IOException e) {
            e.printStackTrace();
            return LayuiDataGridResult.fail();
        }

    }
}
